package org.xukai.remoting.io.nio.weiyi;

import org.apache.commons.lang.StringUtils;

import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @ Type : com.cloud.tool.socket
 * @ Author : TimLi
 * @ Desc :
 * @ Date : 2016-09-28 16:09
 */
public class StringTranUtils {


    public static  short ByteArrayToShort(byte[] bArr,int index) {

        return (short) (((bArr[index+1] & 0xff) << 8) | ((bArr[index] & 0xff) << 0));
    }

    public static  short ByteArrayToUnShort(byte[] bArr,int index) {

        return (short) ((bArr[index] & 0xff) << 0);
    }


    public static String StringToDate(String year,String day,String mon){
        return year+(mon.length()==1?"0"+mon:mon)+(day.length()==1?"0"+day:day);
    }
    /**
     * 将byte数组转化成String,为了支持中文，转化时用GBK编码方式
     */
    public static  String ByteArraytoString(byte[] valArr,int maxLen,int index) {
        String result=null;
        int infexfor=0;
        int count=index;
        while(infexfor < valArr.length && infexfor < maxLen) {
            if(valArr[count] == 0) {
                break;
            }
            infexfor++;
            count++;
        }
        byte[] temp = new byte[infexfor];
        System.arraycopy(valArr, index, temp, 0, infexfor);
        try {
            result= new String(temp,"utf-8");
        } catch (UnsupportedEncodingException e) {

        }
        return result;
    }

    public static List<String> ByteToList(byte[] body, int index, int oneSpace, int twoSpace) {
        List<String> list = new ArrayList<>();
        int length = 0;
        for (int i = 0; i < oneSpace; i++) {
            StringBuffer buffer = new StringBuffer();
            for (int j = 0; j < twoSpace; j++) {
                buffer.append(ByteArrayToShort(body, index + length)).append(",");
                length = length + 2;
            }
            list.add(buffer.substring(0, buffer.length() - 1));
        }
        return list;
    }




    /**
     * 获取header
     * @param b
     * @return
     */
    public static WanPacketHeader ByteToHeader(byte[] b) {
        WanPacketHeader header=new WanPacketHeader();
        header.setnPldType(Byte.toUnsignedInt(b[3]));
        header.setnPldLen(ByteArrayToShort(b,4));
        return header;
    }

    public static WanPatientInfo ByteToInfo(byte[] body) {
        WanPatientInfo patientInfo = new WanPatientInfo();
        patientInfo.setName(ByteArraytoString(body, 20, 0));
        patientInfo.setDrName(ByteArraytoString(body, 20, 20));
        patientInfo.setDeptName(ByteArraytoString(body, 20, 40));
        patientInfo.setRecNo(ByteArraytoString(body, 20, 60));
        patientInfo.setBirthDate(StringToDate(Short.toString(ByteArrayToShort(body, 80)), Short.toString
                (ByteArrayToUnShort(body, 82)), Short.toString(ByteArrayToUnShort(body, 83))));

        patientInfo.setEnterDate(StringToDate(Short.toString(ByteArrayToShort(body, 84)), Short.toString
                (ByteArrayToUnShort(body, 86)), Short.toString(ByteArrayToUnShort(body, 87))));
   //     patientInfo.setStature(ByteArrayToShort(body, 88));
   //     patientInfo.setAvoird(ByteArrayToShort(body, 90));
        patientInfo.setnChnlIdx(ByteArrayToShort(body, 92));
        patientInfo.setnStatUnit(ByteArraytoString(body, 1, 94));
        patientInfo.setnAvoiUnit(ByteArraytoString(body, 1, 95));
  //      patientInfo.setnSex(ByteArraytoString(body, 1, 96));
  //      patientInfo.setnBlood(ByteArraytoString(body, 1, 97));
   //     patientInfo.setnType(ByteArraytoString(body, 1, 98));
        patientInfo.setRemark(ByteArraytoString(body, 1, 99));
   //     patientInfo.setSzBedInfo(ByteArraytoString(body, 20, 100));
   //     patientInfo.setSzAddress(ByteArraytoString(body, 32, 120));
        patientInfo.setAge(StringTranUtils.ageByBrith(patientInfo.getBirthDate()));
  //      patientInfo.setnSex(patientInfo.getnSex().equals("0")?"男":patientInfo.getnSex().equals("1")?"女":"未知");
        return patientInfo;
    }

    public static WanMedPara ByteToMedPara(byte[] body) {
        WanMedPara para=new WanMedPara();
        para.setHdr(ByteArrayToShort(body, 0));
        para.setSys(ByteArrayToShort(body, 2));
        para.setDia(ByteArrayToShort(body, 4));
        para.setMap(ByteArrayToShort(body, 6));
        para.setSpo2(ByteArrayToShort(body, 8));
        para.setPr(ByteArrayToShort(body, 10));
        para.setRr(ByteArrayToShort(body, 12));
        para.setTemp(ByteArrayToShort(body, 14));
        para.setReserve(ByteArraytoString(body, 32, 16));
        return para;
    }

    public static WanEcgWave ByteToWave(byte[] body) {
         WanEcgWave wanEcgWave=new WanEcgWave();
        wanEcgWave.setSequence(ByteArrayToShort(body, 0));
        wanEcgWave.setRemark(ByteArraytoString(body, 6, 2));
        wanEcgWave.setWaveL(ByteToList(body, 8, 6, 100));
       // wanEcgWave.setWaveV(ByteToArray(body,608,6,100));
        return wanEcgWave;
    }

    public static WanSpO2Wave ByteToSpO2Wave(byte[] body) {
        WanSpO2Wave wanSpO2Wave=new WanSpO2Wave();
        wanSpO2Wave.setSequence(ByteArrayToShort(body, 0));
        wanSpO2Wave.setRemark(ByteArraytoString(body, 2, 2));
        short[] wave=new short[100];
        for(int i=0;i<100;i++){
            wave[i]=ByteArrayToUnShort(body, 4 + i);
        }
        wanSpO2Wave.setWave(wave);
        return wanSpO2Wave;
    }


    public static WanRespWave ByteToRespWave(byte[] body) {
     WanRespWave respWave=new WanRespWave();
        respWave.setSequence(ByteArrayToShort(body, 0));
        respWave.setRemark(ByteArraytoString(body, 2, 2));
        short[] wave=new short[100];
        for(int i=0;i<100;i++){
            wave[i]=ByteArrayToUnShort(body, 4 + i);
        }
        respWave.setWave(wave);
        return respWave;
    }


    public static void ByteToPatientSupplyWave(byte[] body){

    }


    public static Integer ageByBrith(String brithDate){
        if(StringUtils.isEmpty(brithDate)){
            return 0;
        }
        try {
            return     getAge(parse(brithDate));
        } catch (Exception e) {
             return 0;
        }
    }

    public static Date parse(String strDate)  {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            return sdf.parse(strDate);
        } catch (ParseException e) {
             return null;
        }
    }

    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            }else{
                age--;
            }
        }
        return age;
    }

    /**
     * 填充患者个人信息
     * @param body
     * @return
     */
    public static WanPatientInfo ByteToSupplyInfo(byte[] body) {
        WanPatientInfo patientInfo=new WanPatientInfo();
        String info =null;
        try {
              info = ByteArraytoString(body, body.length, 0);
            if (StringUtils.isNotEmpty(info)) {
                String[] wanArr = info.split("\\r\\n");
                patientInfo.setDevId(arraySplit(wanArr[0]));
                patientInfo.setName(arraySplit(wanArr[1]));
                patientInfo.setSex(sexDesc(arraySplit(wanArr[2])));
                patientInfo.setBlood(arraySplit(wanArr[3]));
                patientInfo.setType(personType(arraySplit(wanArr[4])));
                patientInfo.setBirthDate(arraySplit(wanArr[5]));
                patientInfo.setHeight(arraySplit(wanArr[6]));
                patientInfo.setWeight(arraySplit(wanArr[7]));
                patientInfo.setCertId(arraySplit(wanArr[8]));
                patientInfo.setPhone(arraySplit(wanArr[9]));
                patientInfo.setRecId(arraySplit(wanArr[10]));
                patientInfo.setBedInfo(arraySplit(wanArr[11]));
                patientInfo.setEnterDate(arraySplit(wanArr[12]));
                patientInfo.setDoctorId(arraySplit(wanArr[13]));
                patientInfo.setDrName(arraySplit(wanArr[14]));
                patientInfo.setHospitalId(arraySplit(wanArr[15]));
                patientInfo.setHospitalName(arraySplit(wanArr[16]));
                patientInfo.setDeptId(arraySplit(wanArr[17]));
                patientInfo.setDeptName(arraySplit(wanArr[18]));
                patientInfo.setAge(StringTranUtils.ageByBrith(patientInfo.getBirthDate()));
                return patientInfo;
            }
        }catch (Exception e){

        }
        return null;
    }

    private static String personType(String s) {
        return "a".equalsIgnoreCase(s)?"成人":"c".equalsIgnoreCase(s)?"儿童":"n".equalsIgnoreCase(s)?"新生儿童":"未知";
    }

    private static String sexDesc(String s) {
       return  "m".equalsIgnoreCase(s)?"男":"f".equalsIgnoreCase(s)?"女":"未知";
    }


    public static String arraySplit(String param){
        if(StringUtils.isNotBlank(param)&&param.contains(":")){
              return param.split(":")[1];
        }
        return null;
    }
}
